package Servants;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import rm1.Message;

import core.Localmessage;

public class UDP_Replica1_Lisener extends Thread
{
	/** General Declaration **/
	int port = 0;
	MyServiceServerImpl server = null;
	
	public  UDP_Replica1_Lisener(MyServiceServerImpl Server)
	{
		this.server = Server;
		switch(this.server.getName())
		{
		case "montreal":
			port = 6792;
			break;
		case "toronto":
			port = 6793;
			break;
		case "vancouver":
			port = 6794;
			break;
			
		}
	}
	
	public void run()
	{
		Message mes = new Message();

		
		
		DatagramSocket aSocket = null;
		try{
	    	aSocket = new DatagramSocket(port);
					// create socket at agreed port
			byte[] buffer = new byte[1000];
			System.out.println("and UDP also ready ...");
 			while(true){
 				DatagramPacket request = new DatagramPacket(buffer, buffer.length);
  				aSocket.receive(request);   
  				mes.parseMessage(request.getData());
  				switch(mes.getRequestType())
  				{
  				case"buy":
  					this.server.buy(mes.getCustomerID(), mes.getItemID(), mes.getNumberOfItems());
  					break;
  				case"return":
  					this.server.returnItem(mes.getCustomerID(),mes.getItemID(), mes.getNumberOfItems());
  					break;
  				case "checkStock":
  					this.server.checkStock(mes.getItemID());
  					break;
  				case "exchange":
  					this.server.exchange(mes.getCustomerID(), mes.getBoughtItemID(),mes.getBoughtNumber(),
  							mes.getItemID(),mes.getNumberOfItems());
  					break;
  				}
    		}
		}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
		}catch (IOException e) {System.out.println("IO: " + e.getMessage());
		}finally {if(aSocket != null) aSocket.close();}

	}


}
